﻿using MySql.Data.MySqlClient;
using System.Text;

namespace Tools.Android
{
    public class EntityConverter
    {

        public string ConvertToJavaEntity(string connectionString, string tableName, string dataBase)
        {
            var columns = GetTableColumns(connectionString, tableName, dataBase);

            var sb = new StringBuilder();
            string className = ToPascalCase(tableName);


            // 类注释
            sb.AppendLine("/**");
            sb.AppendLine($" *  {tableName}");
            sb.AppendLine(" */");

            // 类注解
            sb.AppendLine("@Entity");
            sb.AppendLine($"@Table(name = \"{tableName}\")");
            sb.AppendLine($"public class {className} {{");
            sb.AppendLine();


            string[] _replaceWords = { "Id", "CreateTime", "UpdateTime", "CreateUserId", "CreateUserName", "UpdateUserId", "UpdateUserName" };

            //                    var res = _dirtyWords.Any(x => trNode.InnerText.Contains(x));       //true


            // 处理每个字段
            foreach (var col in columns)
            {
                string fieldName = FirstCharToLower(col.ColumnName);
                string javaType = MapType(col.DataType);


                var res = _replaceWords.Any(x => fieldName.ToLower().Contains(x.ToLower()));
                if (!res)
                {
                    // 字段注释
                    sb.AppendLine($"    /* {col.DataDesc} */");
                    // 字段定义
                    sb.AppendLine($"    private {javaType} {fieldName};");
                    sb.AppendLine();
                }
            }

            // 生成Getter/Setter
            foreach (var col in columns)
            {
                string fieldName = ToCamelCase(col.ColumnName);
                string filedName2 = FirstCharToLower(col.ColumnName);
                string capitalized = Capitalize(fieldName);
                string javaType = MapType(col.DataType);

                var res = _replaceWords.Any(x => fieldName.ToLower().Contains(x.ToLower()));
                if (!res)
                {
                    // Getter
                    sb.AppendLine($"    public {javaType} get{capitalized}() {{");
                    sb.AppendLine($"        return this.{filedName2};");
                    sb.AppendLine("    }");
                    sb.AppendLine();

                    // Setter
                    sb.AppendLine($"    public void set{capitalized}({javaType} {filedName2}) {{");
                    sb.AppendLine($"        this.{filedName2} = {filedName2};");
                    sb.AppendLine("    }");
                    sb.AppendLine();
                }
            }

            sb.AppendLine("}");
            return sb.ToString();
        }

        public static string FirstCharToLower(string input)
        {
            if (string.IsNullOrEmpty(input))
                return input;

            if (input.Length == 1)
                return input.ToLower();

            return char.ToLower(input[0]) + input.Substring(1);
        }



        private List<ColumnInfo> GetTableColumns(string connStr, string tableName, string dataBase)
        {
            var columns = new List<ColumnInfo>();

            using var conn = new MySqlConnection(connStr);
            conn.Open();


            // 查询列信息
            string sql = $@"SELECT 
                            COLUMN_NAME, 
                            DATA_TYPE,
                            COLUMN_COMMENT,
                            COLUMN_KEY = 'PRI',
                            EXTRA LIKE '%auto_increment%'
                            FROM INFORMATION_SCHEMA.COLUMNS 
                            WHERE TABLE_NAME = '{tableName}' AND TABLE_SCHEMA ='{dataBase}'";

            using var cmd = new MySqlCommand(sql, conn);
            cmd.Parameters.AddWithValue($"{tableName}", tableName);

            using var reader = cmd.ExecuteReader();
            while (reader.Read())
            {

                columns.Add(new ColumnInfo
                {
                    ColumnName = reader.GetString(0),
                    DataType = reader.GetString(1),
                    DataDesc = reader.GetString(2),
                    IsPrimaryKey = reader.GetUInt64(3) == 1 ? true : false,
                    IsAutoIncrement = reader.GetUInt64(4) == 1 ? true : false,
                });
            }

            return columns;
        }

        private string MapType(string mysqlType)
        {
            // 去除长度信息（如VARCHAR(255)）
            string baseType = mysqlType.Split('(')[0];
            return DictionaryMappings.AndroidStudioDictionaryTypeMap.TryGetValue(baseType, out string javaType)
                ? javaType : "Object";
        }

        private string ToPascalCase(string input)
        {
            StringBuilder sb = new StringBuilder();
            foreach (string part in input.Split('_'))
            {
                if (part.Length > 0)
                    sb.Append(char.ToUpper(part[0]) + part.Substring(1).ToLower());
            }
            return sb.ToString();
        }

        private string ToCamelCase(string input)
        {
            string pascal = ToPascalCase(input);
            return char.ToLower(pascal[0]) + pascal.Substring(1);
        }

        private string Capitalize(string input)
            => char.ToUpper(input[0]) + input.Substring(1);
    }


}